package com.uestc.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileComparator {

    public static boolean areFilesIdentical(File file1, File file2) {
        try {
            // 获取文件的哈希值
            byte[] checksum1 = calculateChecksum(file1);
            byte[] checksum2 = calculateChecksum(file2);

            // 比较两个哈希值
            return java.util.Arrays.equals(checksum1, checksum2);
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static byte[] calculateChecksum(File file) throws IOException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        FileInputStream fis = new FileInputStream(file);

        byte[] byteArray = new byte[1024];
        int bytesCount = 0;

        // 读取文件内容并更新哈希值
        while ((bytesCount = fis.read(byteArray)) != -1) {
            digest.update(byteArray, 0, bytesCount);
        }

        fis.close();

        // 返回文件的哈希值
        return digest.digest();
    }

    public static void main(String[] args) {
        File file1 = new File("path/to/file1");
        File file2 = new File("path/to/file2");

        if (areFilesIdentical(file1, file2)) {
            System.out.println("文件相同");
        } else {
            System.out.println("文件不同");
        }
    }
}